package com.useeinfo.oa.open.api.repairOrder;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.DateTimeUtils;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.AreaBiz;
import com.useeinfo.oa.modules.base.biz.EnterpriseBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Position;
import com.useeinfo.oa.modules.inspection.biz.InspectionOrderBiz;
import com.useeinfo.oa.modules.maintaining.biz.MaintainOrderBiz;
import com.useeinfo.oa.modules.repair.biz.RepairFocusBiz;
import com.useeinfo.oa.modules.repair.biz.RepairOrderBiz;
import com.useeinfo.oa.modules.repair.entity.RepairFocus;
import com.useeinfo.oa.modules.repair.entity.RepairOrder;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/repairDashboardReport")
public class RepairDashboardReportAPI {
    @Autowired
    private EnterpriseBiz enterpriseBiz;
    @Autowired
    private RepairOrderBiz repairOrderBiz;
    @Autowired
    private RepairFocusBiz repairFocusBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private InspectionOrderBiz inspectionOrderBiz;
    @Autowired
    private MaintainOrderBiz maintainOrderBiz;
    @Autowired
    private AreaBiz areaBiz;
    @Autowired
    private HttpServletRequest request;

    /**
     * 维修工单(今日)
     */
    @RequestMapping(value = "/repairOrderCount")
    public ResultDto repairOrderCount(@RequestParam(value = "enterpriseId", required = false) String enterpriseId) {
        JSONObject data = new JSONObject();
        if (enterpriseId == null) {
            return ResultUtil.success(data);
        }
        //获取下级企业ids（包括自己）
        String ids = enterpriseBiz.childrenIds(enterpriseId);
        data = repairOrderBiz.repairOrderCount(ids);
        return ResultUtil.success(data);
    }

    /**
     * 设备故障发生次数TOP10
     */
    @RequestMapping(value = "/repairTop10")
    public ResultDto repairTop10(@RequestParam(value = "enterpriseId", required = false) String enterpriseId,
                                 @RequestParam(value = "type", required = false) String type) {
        JSONObject data = new JSONObject();
        JSONArray rows = new JSONArray();
        if (enterpriseId == null) {
            data.put("rows", rows);
            return ResultUtil.success(data);
        }
        //获取下级企业ids（包括自己）
        String ids = enterpriseBiz.childrenIds(enterpriseId);
        Date nowTime = new Date();
        String startDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getBeginOfDay(nowTime));
        String endDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getEndOfDay(nowTime));
        if ("month".equals(type)) {
            startDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getBeginOfDay(DateTimeUtils.getFirstDateOfMonth(nowTime)));
            endDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getEndOfDay(DateTimeUtils.getLastDateOfMonth(nowTime)));
        }
        rows = repairOrderBiz.repairTop10(ids, startDate, endDate);
        data.put("rows", rows);
        return ResultUtil.success(data);
    }

    /**
     * 正在维修中的设备
     */
    @RequestMapping(value = "/repairFacilityCount")
    public JSONObject repairFacilityCount(@RequestParam(value = "enterpriseId", required = false) String enterpriseId) {
        JSONObject jsonObject = new JSONObject();
        if (enterpriseId == null) {
            return jsonObject;
        }
        //获取下级企业ids（包括自己）
        String ids = enterpriseBiz.childrenIds(enterpriseId);
        JSONArray rows = repairOrderBiz.repairFacilityCount(ids);
        jsonObject.put("rows", rows);
        return jsonObject;
    }

    /**
     *
     */
    @RequestMapping(value = "/getOrderList")
    public JSONObject getOrderList(@RequestParam(value = "userId", required = false) String userId,
                                   @RequestParam(value = "pageIndex", required = false) String pageIndexParam,
                                   @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                                   @RequestParam(value = "enterpriseId", required = false) String enterpriseId,
                                   @RequestParam(value = "type", required = false) String type) {
        JSONObject data = new JSONObject();
        data.put("records", 0);
        JSONArray rows = new JSONArray();
        data.put("rows", rows);
        if (StringUtils.isBlank(type)) {
            return data;
        }
        SystemUser user = systemUserBiz.findModel(StringConverters.ToLong(userId));
        Enterprise enterprise = enterpriseBiz.findModel(StringConverters.ToLong(enterpriseId));
        if (user == null || enterprise == null) {
            return data;
        }
        //查关注的工单
        if ("focus".equals(type)) {
            QueryParam queryParamF = new QueryParam(pageIndexParam, pageSizeParam);
            queryParamF.getSqlMap().put("systemUserId", userId);
            queryParamF.getSqlMap().put("AUTOMATIC_REPAIR","AUTOMATIC_REPAIR");
            queryParamF.getSqlMap().put("enterpriseId", enterpriseId);
            List<RepairFocus> repairFocusList = repairFocusBiz.findList(queryParamF);
            if (CollectionUtils.isNotEmpty(repairFocusList)) {
                for (RepairFocus repairFocus : repairFocusList) {
                    if (repairFocus.getRepairOrder() != null) {
                        RepairOrder repairOrder = repairFocus.getRepairOrder();
                        JSONObject json = repairOrder.toJSONObject();
                        JSONArray tags = repairOrderBiz.getTags(repairOrder, user, null);
                        json.put("tags", tags);
                        rows.add(json);
                    }
                }
            }
            //查总数
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("systemUserId", userId);
            queryParam.getSqlMap().put("AUTOMATIC_REPAIR","AUTOMATIC_REPAIR");
            queryParam.getSqlMap().put("enterpriseId", enterpriseId);
            Long records = repairFocusBiz.totalRecord(queryParam.getSqlMap());
            if (records > 0) {
                data.put("records", records);
            }
        }
        //查发起的工单
        if ("create".equals(type)) {
            QueryParam queryParamC = new QueryParam(pageIndexParam, pageSizeParam);
            queryParamC.getSqlMap().put("reportUserID", userId);
            queryParamC.getSqlMap().put("AUTOMATIC_REPAIR","AUTOMATIC_REPAIR");
            queryParamC.getSqlMap().put("enterpriseId", enterpriseId);
            List<RepairOrder> repairOrderList = repairOrderBiz.findList(queryParamC);
            if (CollectionUtils.isNotEmpty(repairOrderList)) {
                for (RepairOrder repairOrder : repairOrderList) {
                    JSONObject json = repairOrder.toJSONObject();
                    JSONArray tags = repairOrderBiz.getTags(repairOrder, user, null);
                    json.put("tags", tags);
                    rows.add(json);
                }
            }
            //查总数
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("reportUserID", userId);
            queryParam.getSqlMap().put("enterpriseId", enterpriseId);
            queryParam.getSqlMap().put("AUTOMATIC_REPAIR","AUTOMATIC_REPAIR");
            Long records = repairOrderBiz.totalRecord(queryParam.getSqlMap());
            if (records > 0) {
                data.put("records", records);
            }
        }
        //查我接单的
        if ("receive".equals(type)) {
            QueryParam queryParamR = new QueryParam(pageIndexParam, pageSizeParam);
            queryParamR.getSqlMap().put("receiveUser", userId);
            queryParamR.getSqlMap().put("enterpriseId", enterpriseId);
            queryParamR.getSqlMap().put("AUTOMATIC_REPAIR","AUTOMATIC_REPAIR");
            List<RepairOrder> repairOrderList = repairOrderBiz.findList(queryParamR);
            if (CollectionUtils.isNotEmpty(repairOrderList)) {
                for (RepairOrder repairOrder : repairOrderList) {
                    JSONObject json = repairOrder.toJSONObject();
                    JSONArray tags = repairOrderBiz.getTags(repairOrder, user, null);
                    json.put("tags", tags);
                    rows.add(json);
                }
            }
            //查总数
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("receiveUser", userId);
            queryParam.getSqlMap().put("enterpriseId", enterpriseId);
            queryParam.getSqlMap().put("AUTOMATIC_REPAIR","AUTOMATIC_REPAIR");
            Long records = repairOrderBiz.totalRecord(queryParam.getSqlMap());
            if (records > 0) {
                data.put("records", records);
            }
        }
        //我审核的
        if ("audit".equals(type)) {
            //查出所属岗位
            QueryParam queryParamA = new QueryParam(pageIndexParam, pageSizeParam);
            queryParamA.getSqlMap().put("auditUserId", userId);
            queryParamA.getSqlMap().put("enterpriseId", enterpriseId);
            queryParamA.getSqlMap().put("AUTOMATIC_REPAIR","AUTOMATIC_REPAIR");
            queryParamA.getSqlMap().put("repairOrderStatus","IN_AUDITING");
            Position position = user.getPosition(enterprise, user.getPositionSet());
            if (position != null) {
                queryParamA.getSqlMap().put("auditPositionId", position.getId() + "");
            }
            List<RepairOrder> repairOrderList = repairOrderBiz.findList(queryParamA);
            if (CollectionUtils.isNotEmpty(repairOrderList)) {
                for (RepairOrder repairOrder : repairOrderList) {
                    JSONObject json = repairOrder.toJSONObject();
                    JSONArray tags = repairOrderBiz.getTags(repairOrder, user, null);
                    json.put("tags", tags);
                    rows.add(json);
                }
            }

            //查总数
            QueryParam queryParam = new QueryParam();
            queryParam.getSqlMap().put("auditUserId", userId);
            queryParam.getSqlMap().put("enterpriseId", enterpriseId);
            queryParam.getSqlMap().put("AUTOMATIC_REPAIR","AUTOMATIC_REPAIR");
            queryParam.getSqlMap().put("repairOrderStatus","IN_AUDITING");
            if (position != null) {
                queryParam.getSqlMap().put("auditPositionId", position.getId() + "");
            }
            Long records = repairOrderBiz.totalRecord(queryParam.getSqlMap());
            if (records > 0) {
                data.put("records", records);
            }
        }
        //待接单的
        if ("waitTaking".equals(type)) {
            ResultDto resultDto = repairOrderBiz.getRepairOrders(pageIndexParam, pageSizeParam, "1", null, user, enterprise, null,null,null,null,null,null,null,null,null);
            JSONObject jsonObject = JSONObject.parseObject(resultDto.getData().toString());
            rows = jsonObject.getJSONArray("rows");
            ResultDto resultDto1 = repairOrderBiz.getRepairOrders("-1", "-1", "1", null, user, enterprise, null,null,null,null,null,null,null,null,null);
            JSONObject jsonObject1 = JSONObject.parseObject(resultDto1.getData().toString());
            JSONArray array = jsonObject1.getJSONArray("rows");
            if (array.size() > 0) {
                data.put("records", array.size());
            }
        }
        data.put("rows", rows);
        return data;
    }

    /**
     * dashboard-故障严重程度
     */
    @RequestMapping(value = "/getTroubleCatDashBoard")
    public ResultDto getTroubleCatDashBoard() {
        Map<String, Object> dataMap = new HashMap<>();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            dataMap.put("enterpriseId", enterprise.getId() + "");
        } else {
            dataMap.put("enterpriseId", null);
        }
        JSONObject rows = new JSONObject();
        JSONArray jsonArray = repairOrderBiz.getFailureSeverityDashBoard(dataMap);
        rows.put("rows", repairOrderBiz.getFailureSeverityDashBoard(dataMap));
        rows.put("total", jsonArray.size());
        return ResultUtil.success(rows);
    }

    /**
     * dashboard-设备故障发生次数统计TOP10
     */
    @RequestMapping(value = "/getStatisticsEquipmentFailuresDashBoard")
    public ResultDto getStatisticsEquipmentFailuresDashBoard() {
        Map<String, Object> dataMap = new HashMap<>();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            dataMap.put("enterpriseId", enterprise.getId() + "");
        } else {
            dataMap.put("enterpriseId", null);
        }
        return ResultUtil.success(repairOrderBiz.getStatisticsEquipmentFailuresDashBoard(dataMap));
    }

    /**
     * dashboard-分区域响应时间
     */
    @RequestMapping(value = "/getSubregionalResponseTimeDashBoard")
    public ResultDto getSubregionalResponseTimeDashBoard() {
        Map<String, Object> dataMap = new HashMap<>();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if (enterprise != null) {
            dataMap.put("enterpriseId", enterprise.getId() + "");
        } else {
            dataMap.put("enterpriseId", null);
        }
        JSONObject rows = new JSONObject();
        rows.put("areaRow", areaBiz.getAreaListByEnterprise(dataMap));
        rows.put("repairOrderRow", repairOrderBiz.getRepairOrderResponseTime(dataMap));
        rows.put("inspectionOrderRow", inspectionOrderBiz.getInspectionOrderResponseTime(dataMap));
        rows.put("maintainOrderRow", maintainOrderBiz.getMaintainOrderResponseTime(dataMap));
        return ResultUtil.success(rows);
    }

    /**
     * 分区域维修完成率
     */
    @RequestMapping(value = "/areaPercent")
    public ResultDto areaPercent(@RequestParam(value = "enterpriseId", required = false) String enterpriseId) {
        JSONObject rows = new JSONObject();
        if (enterpriseId == null) {
            return ResultUtil.success(rows);
        }
        //获取下级企业ids（包括自己）
        String ids = enterpriseBiz.childrenIds(enterpriseId);
        Date nowTime = new Date();
        String startDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getBeginOfDay(nowTime));
        String endDate = DateTimeUtils.formatDateToStringWithTime(DateTimeUtils.getEndOfDay(nowTime));
        rows = repairOrderBiz.areaPercent(ids,startDate,endDate);
        return ResultUtil.success(rows);
    }
}
